package com.greatchn.single_login.config;

import cn.hutool.core.util.StrUtil;
import com.greatchn.single_login.constant.ResultEnum;
import com.greatchn.single_login.exception.ApiException;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @AccDecisionManager: 判断角色属性
 * @author: ZBoHang
 * @time: 2023/2/9 17:02
 */
@Component
public class AccDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {

        for(ConfigAttribute configAttribute : configAttributes){
            //当前url所需要的角色
            String needRole = configAttribute.getAttribute();
            // 访问url的角色和不需要登录角色一致 跳过
            if (StrUtil.equals("ROLE_NO_LOGIN", needRole)) {
                return;
            }
            //判断用户角色是否为url所需角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            for(GrantedAuthority grantedAuthority : authorities){
                if(grantedAuthority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw new ApiException(ResultEnum.NONE_AUTH.getCode(), ResultEnum.NONE_AUTH.getMsg());
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
